<template>
  <div class="chat-interface">
    <div class="chat-header">
      <div class="header-info">
        <el-icon><Robot /></el-icon>
        <span>AI学习助手</span>
      </div>
      <div class="header-actions">
        <el-button type="text" size="small" @click="clearChat">
          <el-icon><Delete /></el-icon>
          清空对话
        </el-button>
      </div>
    </div>
    
    <div class="chat-body" ref="chatBodyRef">
      <div class="chat-messages">
        <div v-if="messages.length === 0" class="empty-chat">
          <el-empty description="开始与AI助手对话吧！">
            <template #image>
              <el-icon size="60"><ChatDotRound /></el-icon>
            </template>
          </el-empty>
        </div>
        
        <div
          v-for="message in messages"
          :key="message.id"
          :class="['message', message.type]"
        >
          <div class="message-avatar">
            <el-avatar :size="36">
              <el-icon v-if="message.type === 'user'"><User /></el-icon>
              <el-icon v-else><Robot /></el-icon>
            </el-avatar>
          </div>
          
          <div class="message-content">
            <div class="message-bubble">
              <div class="message-text" v-html="formatMessage(message.content)"></div>
              <div class="message-time">{{ formatTime(message.time) }}</div>
            </div>
          </div>
        </div>
        
        <!-- 正在输入指示器 -->
        <div v-if="isTyping" class="message ai">
          <div class="message-avatar">
            <el-avatar :size="36">
              <el-icon><Robot /></el-icon>
            </el-avatar>
          </div>
          <div class="message-content">
            <div class="message-bubble">
              <div class="typing-indicator">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <div class="chat-footer">
      <div class="input-area">
        <el-input
          v-model="inputText"
          type="textarea"
          :rows="2"
          placeholder="向AI助手提问..."
          :disabled="isTyping"
          @keydown.enter.exact.prevent="sendMessage"
          @keydown.enter.shift.exact="handleShiftEnter"
          resize="none"
        />
        
        <div class="input-actions">
          <div class="input-tips">
            <span>按 Enter 发送，Shift + Enter 换行</span>
          </div>
          
          <el-button
            type="primary"
            :loading="isTyping"
            :disabled="!inputText.trim()"
            @click="sendMessage"
          >
            <el-icon><Promotion /></el-icon>
            发送
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Robot, Delete, ChatDotRound, User, Promotion
} from '@element-plus/icons-vue'

// Props
const props = defineProps({
  // 消息列表
  messages: {
    type: Array,
    default: () => []
  },
  // 是否正在输入
  isTyping: {
    type: Boolean,
    default: false
  },
  // 占位符文本
  placeholder: {
    type: String,
    default: '向AI助手提问...'
  },
  // 是否禁用输入
  disabled: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['send-message', 'clear-chat'])

// Refs
const chatBodyRef = ref(null)
const inputText = ref('')

// 发送消息
const sendMessage = () => {
  const message = inputText.value.trim()
  if (!message || props.isTyping) return
  
  emit('send-message', message)
  inputText.value = ''
}

// 处理Shift+Enter换行
const handleShiftEnter = (event) => {
  // 允许默认行为（换行）
}

// 清空对话
const clearChat = () => {
  emit('clear-chat')
}

// 滚动到底部
const scrollToBottom = () => {
  if (chatBodyRef.value) {
    nextTick(() => {
      chatBodyRef.value.scrollTop = chatBodyRef.value.scrollHeight
    })
  }
}

// 格式化消息内容
const formatMessage = (content) => {
  if (!content) return ''
  
  // 将换行符转换为<br>
  let formatted = content.replace(/\n/g, '<br>')
  
  // 处理代码块
  formatted = formatted.replace(/```([\s\S]*?)```/g, '<pre><code>$1</code></pre>')
  
  // 处理行内代码
  formatted = formatted.replace(/`([^`]+)`/g, '<code>$1</code>')
  
  // 处理加粗
  formatted = formatted.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
  
  // 处理斜体
  formatted = formatted.replace(/\*(.*?)\*/g, '<em>$1</em>')
  
  return formatted
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
}

// 监听消息变化，自动滚动到底部
watch(
  () => props.messages,
  () => {
    scrollToBottom()
  },
  { deep: true }
)

// 监听输入状态变化，自动滚动到底部
watch(
  () => props.isTyping,
  () => {
    if (props.isTyping) {
      scrollToBottom()
    }
  }
)

// 暴露方法
defineExpose({
  scrollToBottom,
  clearInput: () => {
    inputText.value = ''
  }
})
</script>

<style scoped>
.chat-interface {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: white;
  border-radius: 8px;
  overflow: hidden;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
}

.header-info {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  color: #303133;
}

.header-info .el-icon {
  color: #409eff;
}

.chat-body {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background: #fafafa;
}

.chat-messages {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.empty-chat {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #909399;
}

.message {
  display: flex;
  gap: 12px;
  max-width: 80%;
}

.message.user {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.message.user .message-bubble {
  background: #409eff;
  color: white;
}

.message.ai .message-bubble {
  background: white;
  color: #303133;
  border: 1px solid #e4e7ed;
}

.message-content {
  flex: 1;
}

.message-bubble {
  padding: 12px 16px;
  border-radius: 12px;
  position: relative;
  word-break: break-word;
  line-height: 1.5;
}

.message-text {
  margin-bottom: 4px;
}

.message-text :deep(pre) {
  background: rgba(0, 0, 0, 0.1);
  padding: 8px;
  border-radius: 4px;
  margin: 8px 0;
  overflow-x: auto;
}

.message-text :deep(code) {
  background: rgba(0, 0, 0, 0.1);
  padding: 2px 4px;
  border-radius: 2px;
  font-family: 'Courier New', monospace;
}

.message-time {
  font-size: 12px;
  opacity: 0.7;
}

.typing-indicator {
  display: flex;
  gap: 4px;
  align-items: center;
  padding: 8px 0;
}

.typing-indicator span {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: #909399;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

.chat-footer {
  padding: 16px 20px;
  background: white;
  border-top: 1px solid #e4e7ed;
}

.input-area {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.input-tips {
  font-size: 12px;
  color: #909399;
}

/* 滚动条样式 */
.chat-body::-webkit-scrollbar {
  width: 6px;
}

.chat-body::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.chat-body::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.chat-body::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>
